<template>
  <div class="upkeep-item" style="width: 650px;">
    <el-button 
      v-if="!obj" 
      type="primary" 
      icon="el-icon-plus" 
      @click="setAddNewStationMd({state: true})">
      添加维修站点
    </el-button>

    <el-form 
      :model="fm.ps" 
      :ref="fm.fname" 
      label-width="100px" 
      size="medium"
      style="margin-top: 10px">
      <el-row>
        <el-col :span="12">
          <el-form-item 
            label="保养日期" 
            prop="repairDate" 
            :rules="[{ required: true, message: '请选择保养日期', trigger: 'blur' }]">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="fm.ps.repairDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item 
            label="报账车辆" 
            prop="plateNum" 
            :rules="[{ required: true, message: '请选择报账车辆', trigger: 'blur' }]">
            <el-select 
              style="width: 100%" 
              v-model="fm.ps.plateNum" 
              clearable filterable 
              placeholder="报账车辆">
              <el-option 
                v-for="item in carNumList" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item 
            label="报账驾驶员" 
            prop="driverUname" 
            :rules="[{ required: true, message: '请选择报账驾驶员', trigger: 'blur' }]">
            <el-select 
              style="width: 100%" 
              v-model="fm.ps.driverUname" 
              clearable filterable 
              placeholder="报账驾驶员">
              <el-option 
                v-for="it in driverList"
                :key="it.uname"
                :label="it.realName"
                :value="it.uname">
                <span>{{it.realName}}</span>
                <span>{{it.phone}}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item 
            label="车辆公里数" 
            prop="currKm"
            :rules="[
              {required: true, message: '请输入公里数', trigger: 'blur'},
              this.$rules.isPosInt('公里数必须大于0')
            ]">
            <el-input 
              maxlength="7"
              placeholder="当前车辆公里数" 
              v-model="fm.ps.currKm">
              <b slot="suffix" class="c-black">公里</b>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item 
            label="维修站点" 
            prop="repairStationId" 
            :rules="[{ required: true, message: '请选择维修站点', trigger: 'blur' }]">
            <el-select 
              style="width: 100%" 
              v-model="fm.ps.repairStationId" 
              clearable filterable 
              placeholder="维修站点">
              <el-option 
                v-for="item in repairOptions"
                :key="item.id"
                :label="item.unitName"
                :value="item.id">
                <span>{{item.unitName}}</span>
                <span>{{item.baseUserId.realName}}-{{item.baseUserId.phone}}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item 
            label="支付方式" 
            prop="repairPayWay" 
            :rules="[{ required: true, message: '请选择支付方式', trigger: 'blur' }]">
            <el-select 
              style="width: 100%" 
              v-model="fm.ps.repairPayWay" 
              clearable 
              placeholder="支付方式">
              <el-option label="记账" value="JZ_PAY"></el-option>
              <el-option label="现金" value="CASH_PAY"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item 
            label="维修金额" 
            prop="repairMoney"
            :rules="[
              {required: true, message: '请输入维修金额', trigger: 'blur'},
              this.$rules.isFloat('维修金额必须大于0')
            ]">
            <el-input 
              maxlength="6"
              placeholder="维修金额" 
              v-model="fm.ps.repairMoney">
              <b slot="suffix" class="c-black">元</b>
            </el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item 
            label="图片上传" 
            prop="repairUrl" 
            :rules="[{ validator: fm.valRepairUrl, trigger: 'change' }]"
            required>
            <UploadImg
              style="display:inline-block;margin-right: 20px;"
              v-for="(it,index) in fm.ps.repairUrl"
              :key="index"
              imgName="repairUrl"
              @getImgUrl="(data) => setImgUrl(data,index)"
              url="/company/upload"
              :ps="{userName: uname}"
              :src="fileBaseUrl+it.url"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item 
            type="textarea"
            label="维修项目" 
            prop="repairRemark" 
            :rules="[{ required: true, message: '请输入维修项目', trigger: 'blur' }]">
            <el-input 
              type="textarea"
              placeholder="维修项目" 
              v-model="fm.ps.repairRemark"
              show-word-limit
              maxlength="100"
              :rows="4"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="fm-btn-row">
      <el-button 
        :loading="fm.sb.load" 
        type="primary" 
        icon="el-icon-check" 
        @click="onSubmit">
        {{fm.sb.text}}
      </el-button>
    </div>

    <AddNewStation
      v-if="addNewStationMd.state"
      @myClick="setAddNewStationMd"
    />

  </div>
</template>

<script>
import {mapGetters} from "vuex";
import UploadImg from '@/components/UploadImg';
import AddNewStation from './add-new-station'

import * as commonSer from "@/api/services/common.service";
import * as orderSer from "@/api/services/order.service";
import * as logisticsSer from "@/api/services/logistics.service";

export default {
  name: "UpkeepItem",
  props: {myData: Object},
  computed: {
    ...mapGetters(["uname"]),
  },
  components: { UploadImg, AddNewStation },
  data() {
    // 验证-行程报账凭证图片
    let valRepairUrl = (rule, value, callback) => {
      if(!value[0].url) callback(new Error('请选择图片'));
      callback();
    };
    return {
      // 文件地址前缀
      fileBaseUrl: this.C.fileBaseUrl,

      // 修改对象
      obj: this.myData.obj,

      fm: {
        fname: 'oilItemFm',
        sb: {load: false, text: '提交申请'},
        valRepairUrl,
        ps: {
          // 修改记账记录id
          uid: '', 
          // 车辆当前公里数
          currKm: '', 
          // 驾驶员账号
          driverUname: '',
          // 车牌号 
          plateNum: '', 
          // 加油日期
          repairDate: '', 
          // 维修金额
          repairMoney: '', 
          // 支付方式
          repairPayWay: '', 
          // 维修项目
          repairRemark: '', 
          // 维修站
          repairStationId: '', 
          // 维修图片url
          repairUrl: [{url: ''}], 
        }
      },

      // 新增-维修站点-弹框
      addNewStationMd: {state: false},

      // 维修站点-选择列表
      repairOptions:[],
      // 车牌号-选择列表
      carNumList: [], 
      // 驾驶员-选择列表
      driverList: [], 
    }
  },
  created() {
    console.log('维修报账父级数据:', this.myData);
    const that = this, ps = that.fm.ps, o = that.obj;

    if(o) {
      // 修改记账记录id
      ps.uid = o.id, 
      // 车辆当前公里数
      ps.currKm = o.driverJzRecordId.currentKilo;
      // 驾驶员账号
      ps.driverUname = o.reimUser?.uname || '';
      // 车牌号 
      ps.plateNum = o.plateNum;
      // 加油日期
      ps.repairDate = o.payDate;
      // 维修金额
      ps.repairMoney = o.payMoney;
      // 支付方式
      ps.repairPayWay = o.driverJzRecordId.payWay ? 'CASH_PAY' : 'JZ_PAY';
      // 维修项目
      ps.repairRemark = o.remark;
      // 维修站
      ps.repairStationId = o.driverJzRecordId.stationCustomer.id;
      // 维修图片url
      let repairUrl = [];
      o.reimVoucherUrl.split(',').filter(it => { if(it) repairUrl.push({url: it.indexOf('=') != -1 ? '/kcbFiles'+it.split('=')[1] : it})});
      if(repairUrl.length > 0) {
        // 多增加一个
        if(repairUrl.length < 4) repairUrl.push({url: ''});
        ps.repairUrl = repairUrl;
      }
    }

    // 初始化-基础数据
    this.init();
  },
  methods: {
    init() {
      // 获取-车牌号-选择数据
      logisticsSer.getAllPlateNum({status: 0}).then(res => {
        if(res?.plateNums) this.carNumList = Object.keys(res.plateNums).map((item) => ({
          label: item, value: item,
        }));
      });

      // 获取-驾驶员-选择数据
      commonSer.getDriverDict({}).then((res) => {
        if(res?.data) this.driverList = res.data || [];
      });
      
      // 获取-维修站-选择数据
      commonSer.getCompanyCusList({cusType: 'REPAIR'}).then(res => {
        if(res?.data) this.repairOptions = res.data;
      });
    },

    // 设置-图片选择地址
    setImgUrl(data, index) {
      const that = this, U = that.U, ps = that.fm.ps;

      if (!data.url) {// 如果是删除
        if(ps.repairUrl.length > 1) ps.repairUrl.splice(index, 1);
      }else{
        ps.repairUrl[index].url = data.url;
        if (ps.repairUrl.length < 4) ps.repairUrl.push({url: ''});

        if(ps.repairUrl.length > 0) U.clearFmVali(that, that.fm.fname, `repairUrl`);
      }
    },

    // 显示/隐藏-添加站点-弹框
    setAddNewStationMd(e){
      const that = this, md = that.addNewStationMd;

      if(!e.state){
        if(e.id){
          // 将新的数据加入到站点选择列表第一个，并选中此站点
          this.fm.ps.repairStationId = e.id;

          // 获取-维修站-选择数据
          commonSer.getCompanyCusList({cusType: 'REPAIR'}).then(res => {
            if(res?.data) this.repairOptions = res.data;
          });
        }

        md.state = false;
      }else{
        md.state = true;
      }
    },

    // 提交表单
    onSubmit() {
      let that = this, U = that.U, fm = that.fm, sb = fm.sb, ps = U.scopy(fm.ps);

      console.log('初始提交参数', ps);
      that.$refs[fm.fname].validate((valid) => {
        if (!valid) { return false; } else {
          sb.load = true;

          // 参数处理
          ps.repairUrl = this.fm.ps.repairUrl.map(it => it.url).join(',');
          orderSer.adupRepairReim(ps).then(res => {
            sb.load = false;

            if (res.code !== 1) {
              U.qerror(res.msg);
            }else{
              U.qsuccess(res.msg);

              that.$emit("closeMd");
              that.$emit("reloadDg");
            }
          });
        }
      });
    },


  }
}
</script>

<style scoped>

</style>